import os
import mimetypes
from django.conf import settings
from django.shortcuts import Http404
from django.http import HttpResponse

def serve_apps(request, appname, path):
    """
    Serve static files from media folders in all installed apps

    To use put a URL pattern such as:
        (r'^media/(?P<appname>\w+)/(?P<path>.+)$', 'media.serve_apps')

    Then the media in my_installed_app/media will be available at the url media/my_installed_app

    This view is intended for development purposes only and you should properly configure your
    webserver to serve media in production use.
    """
    for app in settings.INSTALLED_APPS:
        # Split of the last part of the app name; e.g. 'django.contrib.admin' -> 'admin'
        app_short_name = app.rpartition('.')[2]
        if app_short_name == appname:
            # Work out the directory in which this module resides
            mod = __import__(app)
            moddir = os.path.dirname(mod.__file__)
            
            abspath = os.path.join(moddir, 'media', path)
            if not os.path.exists(abspath):
                raise Http404("Could not find media '%s' for app '%s' at location '%s'" % (path, appname, abspath))
            if not os.path.isfile(abspath):
                raise Http404("Media '%s' at '%s' is not a file" % (path, abspath))
            
            # Return the file as a response guessing the mimetype
            mimetype = mimetypes.guess_type(abspath)[0] or 'application/octet-stream'
            contents = open(abspath, 'rb').read()
            response = HttpResponse(contents, mimetype=mimetype)
            response["Content-Length"] = len(contents)
            return response

    raise Http404("Could not find app of name '%s'" % (appname,))
